package com.ruoyi.project.ledger.service.impl;

import java.util.*;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.ledger.domain.LedgerFile;
import com.ruoyi.project.ledger.mapper.LedgerBusinessAccountMapper;
import com.ruoyi.project.ledger.mapper.LedgerFileMapper;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.ledger.mapper.LedgerBusinessWorkerMapper;
import com.ruoyi.project.ledger.domain.LedgerBusinessWorker;
import com.ruoyi.project.ledger.service.ILedgerBusinessWorkerService;

/**
 * 经营户人员Service业务层处理
 *
 * @author gwc
 * @date 2020-05-08
 */
@Service
public class LedgerBusinessWorkerServiceImpl implements ILedgerBusinessWorkerService
{
    private static final Logger log = LoggerFactory.getLogger(LedgerBusinessWorkerServiceImpl.class);

    @Autowired
    private LedgerBusinessWorkerMapper ledgerBusinessWorkerMapper;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private LedgerFileMapper ledgerFileMapper;
    @Autowired
    private LedgerBusinessAccountMapper ledgerBusinessAccountMapper;

    /**
     * 查询经营户人员
     *
     * @param id 经营户人员ID
     * @return 经营户人员
     */
    @Override
    public LedgerBusinessWorker selectLedgerBusinessWorkerById(Long id)
    {
        LedgerBusinessWorker businessWorker = ledgerBusinessWorkerMapper.selectLedgerBusinessWorkerById(id);
        if(businessWorker != null){
            // 根据id获取岗位信息
            List<String> postList = ledgerBusinessWorkerMapper.selectBusinessWorkerPost(id);
            businessWorker.setPostList(postList);
            if(postList != null && postList.size() > 0){
                List<SysDictData> dictList=  dictDataMapper.selectDictDataByType("bussiness_worker_post");
                StringBuffer sb = new StringBuffer();
                for(String post : postList){
                    for(SysDictData dict : dictList){
                        if(post.equals(dict.getDictValue())){
                            sb.append(dict.getDictLabel()).append(",");
                            break;
                        }
                    }
                }
                if(sb.length() > 0){
                    businessWorker.setPostNames(sb.substring(0,sb.length() - 1));
                }
            }

            // 获取图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("1");      // 经营户人员
            List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList(ledgerFile);
            businessWorker.setImgList(imgList);
        }
        return businessWorker;
    }

    /**
     * 查询经营户人员列表
     *
     * @param ledgerBusinessWorker 经营户人员
     * @return 经营户人员
     */
    @Override
    public List<LedgerBusinessWorker> selectLedgerBusinessWorkerList(LedgerBusinessWorker ledgerBusinessWorker)
    {
        List<LedgerBusinessWorker> list = ledgerBusinessWorkerMapper.selectLedgerBusinessWorkerList(ledgerBusinessWorker);
        if(list != null && list.size() > 0){
            List<SysDictData> dictList=  dictDataMapper.selectDictDataByType("bussiness_worker_post");
            for(LedgerBusinessWorker businessWorker : list){
                // 根据id获取岗位信息
                List<String> postList = ledgerBusinessWorkerMapper.selectBusinessWorkerPost(businessWorker.getId());
                businessWorker.setPostList(postList);
                if(postList != null && postList.size() > 0){
                    StringBuffer sb = new StringBuffer();
                    for(String post : postList){
                        for(SysDictData dict : dictList){
                            if(post.equals(dict.getDictValue())){
                                sb.append(dict.getDictLabel()).append(",");
                                break;
                            }
                        }
                    }
                    if(sb.length() > 0){
                        businessWorker.setPostNames(sb.substring(0,sb.length() - 1));
                    }
                }
            }
        }
        return list;
    }

    /**
     * 新增经营户人员
     *
     * @param ledgerBusinessWorker 经营户人员
     * @return 结果
     */
    @Override
    public int insertLedgerBusinessWorker(LedgerBusinessWorker ledgerBusinessWorker)
    {
        ledgerBusinessWorker.setCreateTime(DateUtils.getNowDate());
        int i = ledgerBusinessWorkerMapper.insertLedgerBusinessWorker(ledgerBusinessWorker);
        if(ledgerBusinessWorker.getPosts() != null && ledgerBusinessWorker.getPosts().length > 0){
            List<Map<String, Object>> workerPostList = new ArrayList<>();
            for(String post : ledgerBusinessWorker.getPosts()){
                Map<String, Object> postMap = new HashMap<>();
                postMap.put("businessWorkerId", ledgerBusinessWorker.getId());
                postMap.put("post", post);
                workerPostList.add(postMap);
            }
            ledgerBusinessWorkerMapper.batchInsertBusinessWorkerPost(workerPostList);
        }
        // 添加图片
        if(ledgerBusinessWorker.getImgs() != null && ledgerBusinessWorker.getImgs().length > 0){
            for(String path : ledgerBusinessWorker.getImgs()){
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("1");    // 经营户人员
                ledgerFile.setLedgerId(ledgerBusinessWorker.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerBusinessWorker.getCreateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 修改经营户人员
     *
     * @param ledgerBusinessWorker 经营户人员
     * @return 结果
     */
    @Override
    public int updateLedgerBusinessWorker(LedgerBusinessWorker ledgerBusinessWorker)
    {
        ledgerBusinessWorker.setUpdateTime(DateUtils.getNowDate());
        int i = ledgerBusinessWorkerMapper.updateLedgerBusinessWorker(ledgerBusinessWorker);
        // 根据经营户人员id删除人员岗位关系
        ledgerBusinessWorkerMapper.deletePostByBusinessWorkerId(ledgerBusinessWorker.getId());
        if(ledgerBusinessWorker.getPosts() != null && ledgerBusinessWorker.getPosts().length > 0){
            List<Map<String, Object>> workerPostList = new ArrayList<>();
            for(String post : ledgerBusinessWorker.getPosts()){
                Map<String, Object> postMap = new HashMap<>();
                postMap.put("businessWorkerId", ledgerBusinessWorker.getId());
                postMap.put("post", post);
                workerPostList.add(postMap);
            }
            ledgerBusinessWorkerMapper.batchInsertBusinessWorkerPost(workerPostList);
        }
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(ledgerBusinessWorker.getId());
        ledgerFile.setLedgerType("1");      // 经营户人员
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        if(ledgerBusinessWorker.getImgs() != null && ledgerBusinessWorker.getImgs().length > 0){
            for(String path : ledgerBusinessWorker.getImgs()){
                ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("1");      // 经营户人员
                ledgerFile.setLedgerId(ledgerBusinessWorker.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerBusinessWorker.getUpdateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 批量删除经营户人员
     *
     * @param ids 需要删除的经营户人员ID
     * @return 结果
     */
    @Override
    public int deleteLedgerBusinessWorkerByIds(Long[] ids)
    {
        int i = ledgerBusinessWorkerMapper.deleteLedgerBusinessWorkerByIds(ids);
        if(ids.length > 0){
            for(Long id : ids){
                ledgerBusinessWorkerMapper.deletePostByBusinessWorkerId(id);
                // 删除台账图片
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerId(id);
                ledgerFile.setLedgerType("1");      // 经营户人员
                ledgerFileMapper.deleteLedgerImg(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 删除经营户人员信息
     *
     * @param id 经营户人员ID
     * @return 结果
     */
    @Override
    public int deleteLedgerBusinessWorkerById(Long id)
    {
        int i = ledgerBusinessWorkerMapper.deleteLedgerBusinessWorkerById(id);
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("1");      // 经营户人员
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        ledgerBusinessWorkerMapper.deletePostByBusinessWorkerId(id);
        return i;
    }

    @Override
    public String checkWorkerNameUnique(LedgerBusinessWorker ledgerBusinessWorker) {
        int count = ledgerBusinessWorkerMapper.checkWorkerNameUnique(ledgerBusinessWorker);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String importAccount(List<LedgerBusinessWorker> businessWorkerList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(businessWorkerList) || businessWorkerList.size() == 0)
        {
            throw new CustomException("导入经营户人员不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        int i = 1;
        for (LedgerBusinessWorker businessWorker : businessWorkerList){
            i++;
            try{
                if(businessWorker.getBusinessLicenseNo() == null || "".equals(businessWorker.getBusinessLicenseNo())){
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行营业执照号不能为空");
                    continue;
                }
                if(businessWorker.getName() == null || "".equals(businessWorker.getName())){
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行姓名不能为空");
                    continue;
                }
                // 根据营业执照号获取经营户
                LedgerBusinessAccount businessAccount = ledgerBusinessAccountMapper.selectLedgerBusinessAccountByBusinessLicenseNo(businessWorker.getBusinessLicenseNo(),user.getStationId());
                if(businessAccount == null){
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行经营户不存在");
                    continue;
                }
                // 判断该经营户下的人员是否存在
                businessWorker.setBusinessId(businessAccount.getId());
                LedgerBusinessWorker a = ledgerBusinessWorkerMapper.selectLedgerBusinessWorkerByNameAndBusinessId(businessWorker);
                if(a != null){
                    if(isUpdateSupport){     //更新
                        businessWorker.setUpdateId(user.getUserId().toString());
                        businessWorker.setUpdateTime(new Date());
                        businessWorker.setId(a.getId());
                        this.updateLedgerBusinessWorker(businessWorker);
                        // 根据人员id删除岗位信息
                        ledgerBusinessWorkerMapper.deletePostByBusinessWorkerId(a.getId());
                        // 添加人员岗位
                        List<Map<String, Object>> workerPostList = new ArrayList<>();
                        /*
                        if(businessWorker.getIsFr() != null && "是".equals(businessWorker.getIsFr())){    //法人
                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("businessWorkerId", a.getId());
                            postMap.put("post", "1");
                            workerPostList.add(postMap);
                        }
                        if(businessWorker.getIsFzr() != null && "是".equals(businessWorker.getIsFzr())){    //负责人
                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("businessWorkerId", a.getId());
                            postMap.put("post", "2");
                            workerPostList.add(postMap);
                        }
                        if(businessWorker.getIsZby() != null && "是".equals(businessWorker.getIsZby())){    //值班员
                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("businessWorkerId", a.getId());
                            postMap.put("post", "3");
                            workerPostList.add(postMap);
                        }
                        if(businessWorker.getIsCcy() != null && "是".equals(businessWorker.getIsCcy())){    //叉车员
                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("businessWorkerId", a.getId());
                            postMap.put("post", "4");
                            workerPostList.add(postMap);
                        }*/
                        if (StringUtils.isNotBlank(businessWorker.getPostNames())){
                            String[] strings = businessWorker.getPostNames().split(",");
                            for (String s : strings){
                                String dictValue = dictDataMapper.selectDictValue("bussiness_worker_post", s);
                                if (dictValue != null){
                                    Map<String, Object> postMap = new HashMap<>();
                                    postMap.put("businessWorkerId", a.getId());
                                    postMap.put("post", dictValue);
                                    workerPostList.add(postMap);
                                }

                            }
                        }
                        if(workerPostList != null && workerPostList.size() > 0){
                            ledgerBusinessWorkerMapper.batchInsertBusinessWorkerPost(workerPostList);
                        }
                        successNum++;
                        successMsg.append("<br/>第" + i + "行人员 " + businessWorker.getName() + " 更新成功");
                    }
                } else {
                    businessWorker.setCreateId(user.getUserId().toString());
                    businessWorker.setCreateTime(new Date());
                    this.insertLedgerBusinessWorker(businessWorker);
                    // 添加人员岗位
                    List<Map<String, Object>> workerPostList = new ArrayList<>();
                    /*
                    if(businessWorker.getIsFr() != null && "是".equals(businessWorker.getIsFr())){    //法人
                        Map<String, Object> postMap = new HashMap<>();
                        postMap.put("businessWorkerId", businessWorker.getId());
                        postMap.put("post", "1");
                        workerPostList.add(postMap);
                    }
                    if(businessWorker.getIsFzr() != null && "是".equals(businessWorker.getIsFzr())){    //负责人
                        Map<String, Object> postMap = new HashMap<>();
                        postMap.put("businessWorkerId", businessWorker.getId());
                        postMap.put("post", "2");
                        workerPostList.add(postMap);
                    }
                    if(businessWorker.getIsZby() != null && "是".equals(businessWorker.getIsZby())){    //值班员
                        Map<String, Object> postMap = new HashMap<>();
                        postMap.put("businessWorkerId", businessWorker.getId());
                        postMap.put("post", "3");
                        workerPostList.add(postMap);
                    }
                    if(businessWorker.getIsCcy() != null && "是".equals(businessWorker.getIsCcy())){    //叉车员
                        Map<String, Object> postMap = new HashMap<>();
                        postMap.put("businessWorkerId", businessWorker.getId());
                        postMap.put("post", "4");
                        workerPostList.add(postMap);
                    }*/
                    if (StringUtils.isNotBlank(businessWorker.getPostNames())){
                        String[] strings = businessWorker.getPostNames().split(",");
                        for (String s : strings){
                            String dictValue = dictDataMapper.selectDictValue("bussiness_worker_post", s);
                            if (dictValue != null){
                                Map<String, Object> postMap = new HashMap<>();
                                postMap.put("businessWorkerId", businessWorker.getId());
                                postMap.put("post", dictValue);
                                workerPostList.add(postMap);
                            }

                        }
                    }
                    if(workerPostList != null && workerPostList.size() > 0){
                        ledgerBusinessWorkerMapper.batchInsertBusinessWorkerPost(workerPostList);
                    }
                    successNum++;
                    successMsg.append("<br/>第" + i + "行人员 " + businessWorker.getName() + " 导入成功");
                }
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>第" + i + "行人员 " + businessWorker.getName() + " 导入失败：";
                failureMsg.append(msg + "该行数据信息有误，请仔细检查");
                log.error(msg, e);
            }

        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
